package co.za.itweb.itwebpro;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import co.za.itweb.itwebpro.SimpleGestureFilter.SimpleGestureListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity  {
	//////////////ovo
	static JSONObject jsonObject;
	LinearLayout fragmentHolder;
	static boolean refreshed = false;
	static JSONObject jsonIntroObject;
	static JSONObject sectionsName;
	static List<String> sectionsOrdering;
	static List<String> updatedSections;
	static JSONObject sectionsNameFromCache;
	static String[] feedtitles = null;
	static SharedPreferences myPrefsstat;
	private Dialog dialog;
	Bundle saved;
	JSONArray sectionsOrder;
	ListView verticallist;
	LazyAdapter verticalAdapter;
	private GridAdapter favadapter;
	static Vector<JSONHolder> List = new Vector<JSONHolder>(0);
	boolean[] hidden = null;
	protected static final String PREFS_FAVORITES = "FAVORITES";
	public static JSONObject jArrayFAV = null;
	FavoriteTask ft;
	public FavoritesAdapter favadapterR;
	private InputStream is;
	private String resultFavorite;
	static JSONArray webOrder;
	public static JSONObject websiteData;
	static Dialog dialog2;
	protected static final String LOGIN_NAME = "LOGIN";
	protected static final String FIRSTRUN = "RUNNED";
	private GestureDetector mGestureDetector;
	static String cachedir;
	static String orientation;
	static int imagewidth;
	static String density;
	static int unit;
	public static int GalleryWidth;
	 private static final int SWIPE_MIN_DISTANCE = 120;
     private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	@SuppressLint("WorldReadableFiles")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		saved = savedInstanceState;
		setContentView(R.layout.activity_main);
		myPrefsstat = getSharedPreferences(Overlay.PREFS_NAME,
				MODE_WORLD_READABLE);
		checkTextSize();
		

		if (!hasStorage(true)) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(
					"Your SD card is not writable. Please review your device settings and start application again.")
					.setCancelable(false)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {

									dialog.cancel();
									finish();
								}

							});
			AlertDialog alert = builder.create();
			alert.show();

		} else {

			if (internetConnection()) {
				if (!refreshed) {
					 updateFeeds();
					Intent intent = new Intent(MainActivity.this, Overlay.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivityForResult(intent, 1);
				} else {
					updateFeeds();
				}
			}else{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(
					"There is no internet connection.Please connect to the internet and try again.")
					.setCancelable(false)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {

									dialog.cancel();
									finish();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
		}
		}

		Button refresh = (Button) findViewById(R.id.refresh);

		refresh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),
						Overlay.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivityForResult(intent, 2);
			}
		});

		Button menu = (Button) findViewById(R.id.menu);
		menu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog = new Dialog(MainActivity.this);
				dialog.setContentView(R.layout.dialog_settings);
				dialog.setTitle("ItWeb Pro settings");

				dialog.setCancelable(true);
				Button buttonclose = (Button) dialog
						.findViewById(R.id.closebutton);
				Button buttonmap = (Button) dialog.findViewById(R.id.mapbutton);
				Button buttoninfo = (Button) dialog
						.findViewById(R.id.infobutton);
				Button buttonhelp = (Button) dialog.findViewById(R.id.helpbutton);
				Button buttonsearch = (Button) dialog.findViewById(R.id.searchbutton);

				buttonclose.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						updateFeeds();
						dialog.dismiss();
					}
				});

				buttonmap.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(MainActivity.this, Map.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivityForResult(intent, 12);
						dialog.dismiss();
					}
				});

				buttoninfo.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(MainActivity.this,
								UserData.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivityForResult(intent, 11);
						dialog.dismiss();
					}
				});
				
				
				buttonhelp.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(MainActivity.this,
								Help.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivityForResult(intent, 11);
						dialog.dismiss();
					}
				});
				
				buttonsearch.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(MainActivity.this,
								CitiesActivity.class);
						startActivity(intent);
						dialog.dismiss();
					}
				});
				
				dialog.show();
				showSettings();

			}
			
			

			
		});
		
		

		Button favorites = (Button) findViewById(R.id.favorites);

		favorites.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog = new Dialog(MainActivity.this);
				dialog.setContentView(R.layout.dialog_favorites);
				dialog.setTitle("ITWeb PRO Favorites");
				dialog.setCancelable(true);
				Button buttonclose = (Button) dialog
						.findViewById(R.id.closebutton);
				buttonclose.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {

						dialog.dismiss();
					}
				});
				dialog.show();
				showFavourites();
			}
		});

		 unit=100;
		 if(isXLargeScreen(getApplicationContext())){
			 unit=200;
		 }
		 
		
		 DisplayMetrics metrics = new DisplayMetrics();
         getWindowManager().getDefaultDisplay().getMetrics(metrics);
         if(determineDensity()=="ldpi"){
 			imagewidth=(int) (unit*1.3);
 		}else if(determineDensity()=="mdpi"){
 			imagewidth=(int) (unit);
 		}else if(determineDensity()=="hdpi"){
 			imagewidth=(int) (unit)-(unit/3);
 		}else if(determineDensity()=="xdpi"){
 			imagewidth=(int) (unit)-(unit/2);
 		}
         
         
         GalleryWidth=metrics.widthPixels;
         
         orientation=getOrientation(getApplicationContext());
	}

	public void updateFeeds() {

		File file = new File(Environment.getExternalStorageDirectory()
				.getPath() + "/ITWebPRO/cacheJSON.txt");
		if (file.exists()) {

			try {

				String text = "";
				BufferedReader br = new BufferedReader(new FileReader(file));
				String line;

				while ((line = br.readLine()) != null) {
					text += line;
				}
				br.close();

				JSONObject JO;

				try {
					JO = new JSONObject(text);
					jsonIntroObject = JO;
					sectionsNameFromCache = JO
							.getJSONObject("sections_available");
					sectionsOrder = JO.getJSONArray("sections_order");
					sectionsOrdering = JsonUtil2
							.getStringListFromJsonArray(sectionsOrder);

					generateJSONHolder(sectionsOrdering);
					cachedir=JO.getString("url_cache_images");
					verticallist = (ListView) findViewById(R.id.verticallist);

					verticalAdapter = new LazyAdapter(this, sectionsOrdering);

					verticallist.setAdapter(verticalAdapter);
					verticalAdapter.notifyDataSetChanged();
				
				} catch (JSONException e) {

					e.printStackTrace();
				}

			} catch (IOException e) {
				System.out.println(e.toString());
			}

		}

	}

	
	public void generateJSONHolder(List<String> l) {
		List.clear();
		for (int d = 0; d < l.size(); d++) {
			JSONHolder holder = new JSONHolder();

			try {
				JSONArray JA = jsonIntroObject.getJSONArray(l
						.get(d));

				for (int t = 0; t < JA.length(); t++) {
					JsonItems jsonlist = new JsonItems();
					JSONObject row = (JSONObject) JA.getJSONObject(t);
					jsonlist.setItemId(row.getString("itemID"));
					jsonlist.setTitle(row.getString("title"));
					jsonlist.setCategory(row.getString("section"));
					if (row.has("introImage")) {
						jsonlist.setIntroImage(row.getString("introImage"));
					} else {
						jsonlist.setIntroImage("*");
					}
					if (row.has("introText")) {
						jsonlist.setIntroText(row.getString("introText"));
					} else {
						jsonlist.setIntroText("*");
					}
					holder._itemlist.add(jsonlist);
				}

				List.add(holder);

			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1) {

			if (resultCode == 1) {

				writeToCache();

				Toast.makeText(getApplicationContext(),
						"News are refreshed...", Toast.LENGTH_SHORT).show();
				
					checkFirstRun();
			

			}

			if (resultCode == 0) {
				Toast.makeText(
						getApplicationContext(),
						"There has been a mistake while refreshing news feeds..., please try again",
						Toast.LENGTH_SHORT).show();
				finish();

			}

		}

		if (requestCode == 2) {

			if (resultCode == RESULT_OK) {
				writeToCache();
				Toast.makeText(getApplicationContext(),
						"News are refreshed...", Toast.LENGTH_SHORT).show();

			}

			if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(),
						"There was mistake while refreshing...",
						Toast.LENGTH_SHORT).show();

			}
		}
		
		
		

	}

	private void showSettings() {
		if (dialog.isShowing()) {
			String[] favorites = new String[sectionsOrdering.size()];
			ListView listView2 = (ListView) dialog
					.findViewById(R.id.mysettings);
			for (int y = 0; y < sectionsOrdering.size(); y++) {
				favorites[y] = sectionsOrdering.get(y);
			}

			if (favorites != null) {
				favadapter = new GridAdapter(this, favorites);
				listView2.setAdapter(favadapter);

			}

		}

	}

	static public boolean hasStorage(boolean requireWriteAccess) {

		String state = Environment.getExternalStorageState();
		System.out.println("storage state is " + state);

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			if (requireWriteAccess) {
				boolean writable = checkFsWritable();
				System.out.println("storage writable is " + writable);
				return writable;
			} else {
				return true;
			}
		} else if (!requireWriteAccess
				&& Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			return true;
		}
		return false;
	}

	private static boolean checkFsWritable() {

		String directoryName = Environment.getExternalStorageDirectory()
				.toString() + "/ITWebPRO";
		File directory = new File(directoryName);
		if (!directory.isDirectory()) {
			if (!directory.mkdirs()) {
				return false;
			}
		}
		return directory.canWrite();
	}

	public void writeToCache() {
		if (hasStorage(true)) {
			File storagePath = new File(Environment
					.getExternalStorageDirectory().getPath() + "/ITWebPRO");
			storagePath.mkdirs();
			File oldfile = new File(storagePath + "/cacheJSON.txt");
			oldfile.delete();
			File gpxfile = new File(storagePath + "/cacheJSON.txt");
			FileWriter writer;
			try {
				if (jsonIntroObject != null) {
					writer = new FileWriter(gpxfile);
					String result = jsonIntroObject.toString();
					writer.append(result);
					writer.flush();
					writer.close();
					updateFeeds();// /////////////////////////updating feeds
									// after
					// writing cache
				}

			} catch (IOException e) {

				e.printStackTrace();
			}
		}
	}

	public boolean internetConnection() {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getActiveNetworkInfo();

		return (info != null && info.isConnected());

	}

	public class GridAdapter extends BaseAdapter {
		String[] separated;
		private Activity activity;
		public String[] data;
		public LayoutInflater inflater = null;
		public TextView titletext;
		public ImageLoader imageLoader;
		ArrayList<String> list = new ArrayList<String>();
		JSONArray jsonArray;

		public GridAdapter(Activity a, String[] d) {
			activity = a;
			data = d;
			imageLoader = new ImageLoader(activity.getApplicationContext());
			inflater = (LayoutInflater) activity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			hidden = new boolean[data.length];
			for (int i = 0; i < data.length; i++) {
				hidden[i] = false;
			}
		}

		public int getCount() {
			return data.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View vi = convertView;

			vi = inflater.inflate(R.layout.settings, null);
			// separated = data[position].split("\\|");
			titletext = (TextView) vi.findViewById(R.id.texttitle);
			final ToggleButton togglebutton = (ToggleButton) vi
					.findViewById(R.id.togglebutton);
			try {
				titletext.setText(sectionsNameFromCache
						.getString(data[position]));
			} catch (JSONException e) {

				e.printStackTrace();
			}
			titletext.setTag(data[position]);
			titletext.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {

				}
			});

			try {
				if (checkDisabledFeed(sectionsNameFromCache
						.getString(data[position]))) {
					togglebutton.setChecked(false);
					togglebutton.setTag("false");
				} else {
					togglebutton.setChecked(true);
					togglebutton.setTag("true");
				}
			} catch (JSONException e) {

				e.printStackTrace();
			}
			final int pos = position;
			togglebutton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Vibrator viber = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
					viber.vibrate(300);
					if (v.getTag().equals("true")) {
						try {

							if (addDisabledFeed(sectionsNameFromCache
									.getString(data[pos]))) {
								hidden[pos] = true;

								try {
									if (checkDisabledFeed(sectionsNameFromCache
											.getString(data[pos]))) {
										togglebutton.setChecked(false);
										togglebutton.setTag("false");
										// verticalAdapter.hide(pos);
										System.out
												.println(pos
														+ "---------------------------------------------UPALJENO");

									} else {
										togglebutton.setChecked(true);
										togglebutton.setTag("true");

									}
								} catch (JSONException e) {

									e.printStackTrace();
								}

							}
						} catch (JSONException e) {

							e.printStackTrace();
						}
						togglebutton.setChecked(false);
					} else {
						try {
							if (eraseDisabledFeed(sectionsNameFromCache
									.getString(data[pos]))) {
								hidden[pos] = false;
								// verticalAdapter.unHide(pos);
								try {
									if (checkDisabledFeed(sectionsNameFromCache
											.getString(data[pos]))) {
										togglebutton.setChecked(true);
										togglebutton.setTag("true");
										// verticalAdapter.unHide(pos);

									} else {
										togglebutton.setChecked(true);
										togglebutton.setTag("true");
									}
								} catch (JSONException e) {

									e.printStackTrace();
								}
							} else {

							}
						} catch (JSONException e) {

							e.printStackTrace();
						}
					}

				}

			});

			return vi;
		}
	}

	@SuppressLint("WorldReadableFiles")
	public boolean addDisabledFeed(String feedtitle) {
		JSONArray JArray;
		try {
			SharedPreferences myPrefs = getSharedPreferences(
					Overlay.PREFS_NAME, MODE_WORLD_READABLE);
			String prefName = myPrefs.getString(
					"co.za.itweb.itwebpro.settings", "dis");

			if (prefName.length() > 4) {
				JArray = new JSONArray(prefName);
			} else {
				JArray = new JSONArray();
			}

			JArray.put(feedtitle);
			StringBuilder buf = new StringBuilder();
			buf.append(JArray).append("\n");

			SharedPreferences settings = getSharedPreferences(
					Overlay.PREFS_NAME, 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.clear();
			editor.putString("co.za.itweb.itwebpro.settings", buf.toString());

			editor.commit();
			return true;
		} catch (JSONException e) {
			e.printStackTrace();

		}
		return false;

	}

	public static boolean checkDisabledFeed(String feedidentifier) {

		try {

			String prefName = myPrefsstat.getString(
					"co.za.itweb.itwebpro.settings", "dis");
			if (prefName.length() > 4 ) {
				JSONArray dat;
				dat = new JSONArray(prefName);

				for (int t = 0; t < dat.length(); t++) {
					try {
						String obj = dat.get(t).toString();

						if (obj.equals(feedidentifier)) {

							return true;

						}

					} catch (JSONException e) {
						e.printStackTrace();

					}
				}
			} else {
				return false;
			}
		} catch (JSONException e1) {
			e1.printStackTrace();

		}

		return false;
	}

	@SuppressLint("WorldReadableFiles")
	public boolean eraseDisabledFeed(String feedidentivier) {

		try {
			SharedPreferences myPrefs = getSharedPreferences(
					Overlay.PREFS_NAME, MODE_WORLD_READABLE);
			String prefName = myPrefs.getString(
					"co.za.itweb.itwebpro.settings", "dis");
			prefName = prefName.replaceAll("/", "");
			if (prefName.length() > 4 && prefName != null) {
				JSONArray dat;
				dat = new JSONArray(prefName);
				ArrayList<String> list = new ArrayList<String>();

				for (int t = 0; t < dat.length(); t++) {
					try {
						String obj = dat.get(t).toString();
						if (!obj.equals(feedidentivier)) {
							list.add(obj);
						}

					} catch (JSONException e) {
						e.printStackTrace();

					}
				}

				JSONArray jsArray = new JSONArray(list);
				StringBuilder buf = new StringBuilder();
				buf.append(jsArray).append("\n");

				SharedPreferences settings = getSharedPreferences(
						Overlay.PREFS_NAME, 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.clear();
				editor.putString("co.za.itweb.itwebpro.settings",
						buf.toString());
				editor.commit();

				return true;
			}
		} catch (JSONException e1) {
			e1.printStackTrace();

		}
		return false;

	}

	private void showFavourites() {
		if (dialog.isShowing()) {
			String[] favorites = null;
			ListView listView2 = (ListView) dialog
					.findViewById(R.id.myfavorites);

			SharedPreferences myPrefs = getSharedPreferences(PREFS_FAVORITES,
					MODE_WORLD_READABLE);
			String prefName = myPrefs.getString("co.za.itweb.itwebpro.fav",
					"title");
			prefName = prefName.replaceAll("/", "");

			System.out
					.println("////////////////////////////////////////////////////////////////////////"
							+ prefName);
			JSONArray dat;
			try {
				dat = new JSONArray(prefName);

				favorites = new String[dat.length()];

				for (int t = 0; t < dat.length(); t++) {
					try {
						String obj = dat.getJSONObject(t).getString("title")
								+ "|" + dat.getJSONObject(t).getString("id")
								+ "|" + dat.getJSONObject(t).getString("feed")
								+ "|"
								+ dat.getJSONObject(t).getString("disqus");
						favorites[t] = obj;
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			} catch (JSONException e1) {
				e1.printStackTrace();
			}

			if (favorites != null) {
				favadapterR = new FavoritesAdapter(MainActivity.this, favorites);
				listView2.setAdapter(favadapterR);

			} else {
				Toast.makeText(getApplicationContext(), "No feeds added",
						Toast.LENGTH_SHORT).show();
				dialog.dismiss();
			}

		}

	}

	public class FavoritesAdapter extends BaseAdapter {
		String[] separated;
		private Activity activity;
		public String[] data;
		public LayoutInflater inflater = null;
		public TextView titletext;
		public ImageLoader imageLoader;
		ArrayList<String> list = new ArrayList<String>();
		JSONArray jsonArray;

		public FavoritesAdapter(Activity a, String[] d) {
			activity = a;
			data = d;
			imageLoader = new ImageLoader(activity.getApplicationContext());
			inflater = (LayoutInflater) activity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		}

		public int getCount() {
			return data.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View vi = convertView;
			if (convertView == null)
				vi = inflater.inflate(R.layout.gridbanners, null);
			separated = data[position].split("\\|");
			titletext = (TextView) vi.findViewById(R.id.texttitle);
			ImageButton erasebutton = (ImageButton) vi
					.findViewById(R.id.erasebutton);
			titletext.setText(separated[0]);
			titletext.setTag(separated[1]);
			titletext.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					ft = new FavoriteTask(MainActivity.this, v.getTag()
							.toString(), separated[2], separated[3]);
					ft.execute();
					// MainActivity.dialog2.dismiss();

				}
			});
			erasebutton.setTag(position);

			erasebutton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					JSONArray JArray;
					try {
						SharedPreferences myPrefs = getSharedPreferences(
								PREFS_FAVORITES, MODE_WORLD_READABLE);
						String prefName = myPrefs.getString(
								"co.za.itweb.itwebpro.fav", "title");

						JArray = new JSONArray(prefName);

						List<Object> list = new ArrayList<Object>();

						for (int i = 0; i < JArray.length(); i++) {
							list.add(JArray.get(i));
						}

						if (list.size() > 0) {
							for (int i = 0; i < list.size(); i++) {
								if (Integer.parseInt(v.getTag().toString()) == i) {
									list.remove(i);
								}
							}

							JSONArray jsArray = new JSONArray(list);

							StringBuilder buf = new StringBuilder();

							buf.append(jsArray).append("\n");

							SharedPreferences settings = getSharedPreferences(
									PREFS_FAVORITES, 0);
							SharedPreferences.Editor editor = settings.edit();
							editor.clear();

							// SharedPreferences.Editor editor =
							// getSharedPreferences(MODE_WORLD_READABLE).edit();
							editor.putString("co.za.itweb.itwebpro.fav",
									buf.toString());
							editor.commit();
							showFavourites();
						}

					} catch (JSONException e) {
						e.printStackTrace();
						Toast.makeText(
								getApplicationContext(),
								"Sorry there has been a problem with erasing your favorite news...",
								Toast.LENGTH_SHORT).show();
					}

				}

			});

			return vi;
		}
	}

	private class FavoriteTask extends AsyncTask<Void, Integer, Void> {
		ProgressDialog dialog2;
		String sectionID;
		boolean failed = false;
		int id;

		private Object tinyurlFAV;
		private String bigImageFAV;
		private String tITLEFAV;
		private String TextauthorNameFAV;
		private String introTextFAV;
		private String linkFAV;
		private String disqusFAV;
		private String storyTextFAV;
		private String DateFAV;

		public FavoriteTask(MainActivity activity, String articleId,
				String section, String disqus) {

			this.id = Integer.parseInt(articleId.toString());
			this.sectionID = section;
			this.disqusFAV = disqus;
			dialog2 = new ProgressDialog(activity);
			dialog2.setMessage("Loading Favorite...");
			dialog2.setProgressStyle(ProgressDialog.THEME_HOLO_DARK);
			dialog2.setCancelable(true);
			dialog2.setMax(100);
			dialog2.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					ft.cancel(true);
					Toast.makeText(getApplicationContext(),
							"Loading canceled...", Toast.LENGTH_SHORT).show();
				}
			});
			dialog2.show();

		}

		@Override
		protected Void doInBackground(Void... params) {
			if (parseConfig(id, sectionID)) {
				try {
					jArrayFAV = new JSONObject(resultFavorite);
					tinyurlFAV = jArrayFAV.getString("tinyurl");

					bigImageFAV = jArrayFAV.getString("storyImage");

					tITLEFAV = jArrayFAV.getString("title");

					TextauthorNameFAV = jArrayFAV.getString("authorName");

					introTextFAV = jArrayFAV.getString("introText");
					linkFAV = jArrayFAV.getString("link");

					tinyurlFAV = jArrayFAV.getString("tinyurl");

					if (jArrayFAV.has("disqus")) {
						disqusFAV = "true";

					} else {
						disqusFAV = "false";
					}
					storyTextFAV = jArrayFAV.getJSONArray("storyText")
							.getJSONObject(0).getString("text").toString();

					DateFAV = jArrayFAV.getString("pubDate");

				} catch (JSONException e) {
					jArrayFAV = null;
					is = null;

					Log.e("log_tag", "Error parsing data " + e.toString());
					Intent returnIntent = new Intent();
					returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					setResult(RESULT_CANCELED, returnIntent);

				}
			} else {

				failed = true;
			}

			publishProgress();
			if (isCancelled()) {
				jArrayFAV = null;
				is = null;

				if (dialog2.isShowing()) {
					dialog2.dismiss();
				}

				return null;
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {

		}

		@Override
		protected void onPostExecute(Void result) {
			if (dialog.isShowing()) {
				dialog2.dismiss();
			}
			if (jArrayFAV != null && failed == false) {

				Intent intent = new Intent(getApplicationContext(),
						FavoriteNews.class);
				intent.putExtra("id", id);
				intent.putExtra("feedid", sectionID);
				intent.putExtra("title", tITLEFAV);
				intent.putExtra("image", bigImageFAV);
				intent.putExtra("author", TextauthorNameFAV);
				intent.putExtra("date", DateFAV);
				intent.putExtra("link", linkFAV);
				intent.putExtra("disqus", disqusFAV);
				intent.putExtra("text", storyTextFAV);
				startActivity(intent);
			} else {
				showNotification();
			}

		}

	}

	public void showNotification() {
		Toast.makeText(getApplicationContext(), "Loading failed...",
				Toast.LENGTH_SHORT).show();
	}

	public boolean parseConfig(int itemIdentifier, String section) {
		try {

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(
					"http://itweb.mobi/__itweb_pro/feed/iosv3/_load.php?section="
							+ section + "&itemID=" + itemIdentifier);
			httppost.setHeader("Accept", "application/json");
			httppost.setHeader("Content-type", "application/json");

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");

			}

			resultFavorite = sb.toString();

			// is.close();
			return true;
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
			return false;
		}

	}

	public void checkTextSize() {
		try {
			SharedPreferences myPrefs = getSharedPreferences(
					MainActivity.LOGIN_NAME, MODE_WORLD_READABLE);
			String prefName = myPrefs.getString(
					"co.za.itweb.itwebpro.textsize", "login");
			prefName = prefName.replaceAll("/", "");

			JSONArray dat;
			dat = new JSONArray(prefName);

			for (int t = 0; t < dat.length(); t++) {
				try {
					String obj = dat.getJSONObject(t).getString("text");

					if (obj.length() > 0) {
						News.discrete = Integer.parseInt(obj);
					}

				} catch (JSONException e) {
					e.printStackTrace();

				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();

		}

	}
	
	public void checkFirstRun() {
		try {
			SharedPreferences myPrefs = getSharedPreferences(
					FIRSTRUN, MODE_WORLD_READABLE);
			String prefName = myPrefs.getString(
					"co.za.itweb.itwebpro.firstrun", "run");
			
			JSONArray dat;
			dat = new JSONArray(prefName);

			for (int t = 0; t < dat.length(); t++) {
				try {
					String obj = dat.getJSONObject(t).getString("run");
					System.out.println(obj+"<<<<<<<<<<<<<<<<<<<<<");
					
						
					

				} catch (JSONException e) {
					e.printStackTrace();
					

				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
			addFirstRunFinished();
			Intent intent = new Intent(MainActivity.this, Help.class);
			startActivity(intent);

		}

	}
	
	
	public void addFirstRunFinished() {
		JSONArray JArray;
		SharedPreferences myPrefs = getSharedPreferences(
				FIRSTRUN, MODE_WORLD_READABLE);
		JArray = new JSONArray();
		JArray.put("true");
		StringBuilder buf = new StringBuilder();
		buf.append(JArray).append("\n");

		SharedPreferences settings = getSharedPreferences(
				FIRSTRUN, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.clear();
		editor.putString("co.za.itweb.itwebpro.firstrun", buf.toString());

		editor.commit();
		

	}
	
	
	public  String determineDensity(){
		switch (getResources().getDisplayMetrics().densityDpi) {
		case DisplayMetrics.DENSITY_LOW:
			density="ldpi";
			
		    break;
		case DisplayMetrics.DENSITY_MEDIUM:
			density= "mdpi";
			
			 break;
		case DisplayMetrics.DENSITY_HIGH:
			density= "hdpi";
			
			 break;
		case DisplayMetrics.DENSITY_XHIGH:
			density= "xdpi";
			
			 break;
		}
		return density;
	}

	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			if (dialog != null && dialog.isShowing()) {
				updateFeeds();
				dialog.dismiss();
			} else {
				List.clear();
				refreshed=false;
				jsonObject=null;
				jsonIntroObject=null;
				sectionsName=null;
				sectionsOrdering.clear();
				sectionsNameFromCache=null;
				finish();
			}

		}
		return super.onKeyDown(keyCode, event);
	}

	
	public static boolean isXLargeScreen(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
	}

	@SuppressWarnings("deprecation")
	public  String getOrientation(Context context) {

		final int rotation = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay().getOrientation();
		switch (rotation) {
		case Surface.ROTATION_0:
			return "portrait";
		case Surface.ROTATION_90:
			return "landscape";
		case Surface.ROTATION_180:
			return "portrait";
		default:
			return "landscape";
		}
	}
	
	
	

}
